package gamehandler

import (
	"time"
	cfg "wanyu/server/api/gameapi/gamecfg"
	rpc "wanyu/server/protogo/gameapi"
	"wanyu/server/protogo/public"
	"wanyu/server/protogo/roomsrv"

	"wanyu/server/api/gameapi/roommgr"
	cst "wanyu/server/engine/globaldef/consts"
	log "wanyu/server/engine/wplog"

	sa "wanyu/server/engine/serverapp"
	"wanyu/server/engine/wpcfg"
	errors "wanyu/server/engine/wperror"

	"wanyu/server/api/gameapi/session"

	"github.com/micro/go-micro/broker"
	"github.com/micro/go-micro/client"
	server "github.com/micro/go-micro/server"
)

var (
	roomMgr *roommgr.RoomMgr
)

func Init(microSrv server.Server, microClient client.Client, rpcSrv server.Server, rpcClient client.Client, rm *roommgr.RoomMgr) error {

	roomMgr = rm

	//注册rpc handler
	rpc.RegisterGameHandler(microSrv, new(RpcSrv))
	rpc.RegisterGameEventHandler(rpcSrv, new(StreamSrv))
	public.RegisterPublicsHandler(microSrv, new(Publics))
	//进程启动的时候从roomsrv读取游戏配置
	go getCfgFromRoomSrv(microClient, []*roomsrv.RegGameSvrReq_PlayerInfo{})

	//发布订阅消息，目前暂时只有订阅roomsrv进程启动的消息
	if ec := broker.Init(); nil != ec {
		log.Error("init broker is failed, ", ec)
	}
	if ec := broker.Connect(); nil != ec {
		log.Error("broker connect is failed, ", ec)
	}

	broker.Subscribe(cst.RoomSrvName+".start", func(p broker.Event) error {
		log.Info("recv roomsrv start msg")
		getCfgFromRoomSrv(microClient, roomMgr.GetAllPlayers())
		return nil
	})

	return nil
}

func getCfgFromRoomSrv(rpcCall client.Client, players []*roomsrv.RegGameSvrReq_PlayerInfo) {
	var srvConfig sa.ServiceConf
	ec := wpcfg.ScanNode(cst.ConfigServer, &srvConfig, "microservice")
	errors.Check(nil == ec, errors.ErrorGameCfg, "scan micro service cfg is failed")

	var req roomsrv.RegGameSvrReq
	req.SvrID = srvConfig.SrvName
	req.Type = uint32(cfg.ParseGameType(srvConfig.SrvName))
	req.Player = players

	for {
		rsp, ec := session.GetGameCfg(&req)
		if nil != ec || nil == rsp {
			log.Warnf("get game cfg is failed, ec = %v, rsp = %v", ec, rsp)
			time.Sleep(time.Second * 3)
		} else {
			log.Info("get game cfg is success")
			cfg.SetRawCfg(rsp)
			roomMgr.OnUpdateCfg()
			break
		}
	}
}
